import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { motion, AnimatePresence } from 'framer-motion';

interface AuthModalProps {
  onClose: (success: boolean) => void;
}

const AuthModal: React.FC<AuthModalProps> = ({ onClose }) => {
  const [isLogin, setIsLogin] = useState(true);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [emailHistory, setEmailHistory] = useState<string[]>([]);
  const { login, register, setPassword: resetPassword, sendVerificationCode } = useAuth();

  useEffect(() => {
    const savedEmails = localStorage.getItem('emailHistory');
    if (savedEmails) {
      setEmailHistory(JSON.parse(savedEmails));
    }
  }, []);

  const validatePassword = (pwd: string) => {
    if (pwd.length < 6) {
      setError('密码长度不能小于6位');
      return false;
    }
    setError('');
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setMessage('');

    if (!validatePassword(password)) return;

    try {
      if (isResetPassword) {
        if (password !== confirmPassword) {
          setError('两次输入的密码不一致');
          return;
        }
        await resetPassword(email, password, verificationCode);
        setMessage('密码重置成功，请使用新密码登录');
        setIsResetPassword(false);
        setIsLogin(true);
      } else if (isLogin) {
        await login(email, password);
        onClose(true);
      } else {
        if (password !== confirmPassword) {
          setError('两次输入的密码不一致');
          return;
        }
        await register(email, password, verificationCode);
        setMessage('注册成功，请登录');
        setIsLogin(true);
      }

      // 更新邮箱历史
      if (!emailHistory.includes(email)) {
        const newHistory = [email, ...emailHistory].slice(0, 5);
        setEmailHistory(newHistory);
        localStorage.setItem('emailHistory', JSON.stringify(newHistory));
      }
    } catch (error) {
      console.error('操作失败:', error);
      setError(error instanceof Error ? error.message : '操作失败，请重试。');
    }
  };

  const handleSendVerificationCode = async () => {
    try {
      await sendVerificationCode(email);
      setMessage('验证码已发送到您的邮箱');
    } catch (error) {
      console.error('发送验证码失败:', error);
      setError(error instanceof Error ? error.message : '发送验证码失败，请重试。');
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4"
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.9, opacity: 0 }}
        className="bg-white rounded-lg shadow-xl max-w-md w-full p-8 relative"
      >
        <button
          onClick={() => onClose(false)}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors"
          aria-label="关闭"
        >
          <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
        <h2 className="text-3xl font-bold mb-6 text-center text-gray-800">
          {isResetPassword ? '重置密码' : isLogin ? '登录' : '注册'}
        </h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="relative">
            <input
              type="email"
              placeholder="邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              list="email-history"
            />
            <datalist id="email-history">
              {emailHistory.map((email, index) => (
                <option key={index} value={email} />
              ))}
            </datalist>
          </div>
          <input
            type="password"
            placeholder={isResetPassword ? '新密码' : '密码'}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
            minLength={6}
          />
          <AnimatePresence>
            {(isResetPassword || !isLogin) && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                className="overflow-hidden"
              >
                <input
                  type="password"
                  placeholder="确认密码"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                  minLength={6}
                />
              </motion.div>
            )}
          </AnimatePresence>
          <AnimatePresence>
            {(isResetPassword || !isLogin) && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                className="overflow-hidden"
              >
                <div className="flex space-x-2">
                  <input
                    type="text"
                    placeholder="验证码"
                    value={verificationCode}
                    onChange={(e) => setVerificationCode(e.target.value)}
                    className="flex-grow p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    required
                  />
                  <button
                    type="button"
                    onClick={handleSendVerificationCode}
                    className="px-4 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                  >
                    发送验证码
                  </button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
          {error && <p className="text-red-500 text-sm">{error}</p>}
          {message && <p className="text-green-500 text-sm">{message}</p>}
          <button
            type="submit"
            className="w-full p-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
          >
            {isResetPassword ? '重置密码' : isLogin ? '登录' : '注册'}
          </button>
        </form>
        <div className="mt-4 flex justify-between text-sm">
          {!isResetPassword && (
            <button onClick={() => setIsLogin(!isLogin)} className="text-blue-500 hover:underline">
              {isLogin ? '没有账号？注册' : '已有账号？登录'}
            </button>
          )}
          <button
            onClick={() => setIsResetPassword(!isResetPassword)}
            className="text-blue-500 hover:underline"
          >
            {isResetPassword ? '返回登录' : '忘记密码？'}
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
};

export default AuthModal;